package database

import (
	"chat-app/internal/app/models"
	"fmt"
	"github.com/joho/godotenv"
	"gorm.io/driver/postgres"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"log"
	"os"
)

func InitDB() (*gorm.DB, error) {
	err := godotenv.Load()
	if err != nil {
		log.Fatal("Error loading .env file")
	}

	// 从环境变量获取数据库配置
	dbHost := os.Getenv("DB_HOST")
	//if dbHost == "" {
	//	dbHost = "localhost"
	//}
	dbUser := os.Getenv("DB_USER")
	//if dbUser == "" {
	//	dbUser = "postgres"
	//}
	dbPassword := os.Getenv("DB_PASSWORD")
	dbName := os.Getenv("DB_NAME")
	//if dbName == "" {
	//	dbName = "chat_app"
	//}
	dbPort := os.Getenv("DB_PORT")
	//if dbPort == "" {
	//	dbPort = "5432"
	//}
	fmt.Printf("host=%s user=%s password=%s dbname=%s port=%s sslmode=disable TimeZone=Asia/Shanghai\n",
		dbHost, dbUser, dbPassword, dbName, dbPort)
	// 创建DSN (Data Source Name)
	dsn := fmt.Sprintf("host=%s user=%s password=%s dbname=%s port=%s sslmode=disable TimeZone=Asia/Shanghai",
		dbHost, dbUser, dbPassword, dbName, dbPort)

	// 打开数据库连接
	db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{
		Logger: logger.Default.LogMode(logger.Info), // 开启SQL日志
	})
	if err != nil {
		return nil, fmt.Errorf("failed to connect to database: %w", err)
	}

	// 获取底层sql.DB实例以设置连接池
	sqlDB, err := db.DB()
	if err != nil {
		return nil, err
	}

	// 设置连接池参数
	sqlDB.SetMaxIdleConns(10)  // 空闲连接数
	sqlDB.SetMaxOpenConns(100) // 最大打开连接数

	return db, nil
}

// 数据库迁移（示例）
func MigrateModels(db *gorm.DB) error {
	// 列出所有需要迁移的模型
	modelsToMigrate := []interface{}{
		&models.User{},
		&models.FriendRequest{},
		&models.Friend{},
		&models.Group{},
		&models.GroupMember{},
		&models.Message{},
	}

	for _, model := range modelsToMigrate {
		if err := db.AutoMigrate(model); err != nil {
			return fmt.Errorf("failed to migrate model: %w", err)
		}
	}

	return nil
}
